﻿using System;
using System.Collections.Generic;
using System.Text;
using UMLTouch.Core.Entities;
using System.Threading;

namespace UMLTouch.DomainRecognition
{
    /// <summary>
    /// The Abstract Engine class provides a Producer / Consumer Architecture
    /// For Recognition Engines. it inherits from IEngineOutput en IEngineOutput
    /// So that an Engine becomes a producer (Output) and a consumer (input) 
    /// at the same time.
    /// </summary>
    /// <typeparam name="InputType">the type that the Engine accepts as input</typeparam>
    /// <typeparam name="OutputType">the type that the Engine accepts as output</typeparam>
    public abstract class AbstractEngine<InputType, OutputType> :
        IEngineInput<InputType>, IEngineOutput<OutputType>, IDisposable
        //where InputType : IEngineEntity
        //where OutputType : IEngineEntity
    {
        Queue<InputType> _input;
        const int MAX_THREADS = 1;

        /// <summary>
        /// Gets or Set the Input Queue
        /// </summary>
        protected Queue<InputType> Input
        {
            get { return _input; }
            set { _input = value; }
        }


        List<Thread> _threads;
        List<IEngineInput<OutputType>> _outputs;

        /// <summary>
        /// Gets or Sets the list of possible outputs.
        /// </summary>
        protected List<IEngineInput<OutputType>> Outputs
        {
            get { return _outputs; }
            set { _outputs = value; }
        }

        //lock object used for thread synchronization in the Recognize() method.
        readonly object _locker = new object();

        //int _instanceCount = 0;
        //private int _instanceID;

        /// <summary>
        /// Call this method to input a new value into the Engine
        /// </summary>
        /// <param name="entity">the object to add to input queue</param>
        public void InputItem(InputType entity)
        {

            lock (_locker)
            {
                _input.Enqueue(entity);
                Monitor.Pulse(_locker);
            }

        }

        protected AbstractEngine()
        {
           
            _threads = new List<Thread>();
            _input = new Queue<InputType>();
            _outputs = new List<IEngineInput<OutputType>>();
            PopThread();
        }

        /// <summary>
        /// Adds an output to the Engine
        /// </summary>
        /// <param name="nextEngine">the output to add</param>
        public void AddNextEngine(IEngineInput<OutputType> nextEngine)
        {
            if (nextEngine != null)
                _outputs.Add(nextEngine);
        }
        
        /// <summary>
        /// Creates a new Thread used for the recognition part.
        /// </summary>
        public void PopThread()
        {
            if (_threads.Count < MAX_THREADS)
            {
                Thread RecognitionThread = new Thread(Recognize);
                RecognitionThread.IsBackground = true;
                RecognitionThread.Start();
                _threads.Add(RecognitionThread);
            }
        }

        /// <summary>
        /// This method is the method executed in the Recognition Thread(s).
        /// It retrieves one Item from the queue using the virtual DequeueEntity() method.
        /// The method is TreadSafe using locks and Monitor.Wait
        /// THIS METHOD CONTAINS AN INFINITE LOOP. DON'T CALL IT IN A NON MULTI-THREADED 
        /// SCENARIO.
        /// </summary>
        protected virtual void Recognize()
        {
            //Thread loop
            while (true)
            {
                lock (_locker)
                {
                    while (_input.Count == 0) Monitor.Wait(_locker);
                    InputType tmp = DequeueEntity();
                    if (tmp == null)
                    {
                        ;
                    }
                }
            }
        }

        /// <summary>
        /// Gets the first item from the InputQueue and calls the
        /// SpecificRecognition() Method.
        /// </summary>
        /// <returns>returns the dequeus item</returns>
        public virtual InputType DequeueEntity()
        {
            InputType tmp = _input.Dequeue();
            SpecificRecognition(tmp);
            return tmp;
        }

       
        public abstract void SpecificRecognition(InputType t);

        public virtual void Dispose()
        {
            foreach (var item in _threads)
            {
                item.Abort();
            }
        }

        /// <summary>
        /// Use this method to push the specified object to the inputs
        /// of all the next machines.
        /// </summary>
        /// <param name="output">the object to output</param>
        public virtual void PushOutput(OutputType output)
        {
            foreach (IEngineInput<OutputType> item in _outputs)
            {
                item.InputItem(output);
            }
        }


    }
}
